package com.example.demo.base;

import com.example.demo.common.shiro.ShiroUtils;
import com.example.demo.sys.user.entity.SysUser;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 视图控制器基类
 *
 * @author haocj
 */
@Controller
public class BaseController {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 下面返回ajax信息
     * @return
     */
    public Result success() {
        return Result.success();
    }

    public Result success(String msg) {
        return Result.success(msg);
    }

    public Result success(Object object) {
        return Result.success(object);
    }

    public Result error() {
        return Result.error();
    }

    public Result error(Integer code) {
        return Result.error(code);
    }

    public Result error(Integer code, String msg) {
        return Result.error(code, msg);
    }

    /**
     * 获取session 用户
     * @return
     */
    public SysUser getUser() {
        return ShiroUtils.getUser();
    }

    /**
     * 获取用户id
     * @return
     */
    public String getUserId() {
        return getUser().getId();
    }
}
